﻿//配置textbox
$.fn.validatebox.defaults.validType = "length[1,20]";

//配置combobox
$.fn.combobox.defaults.width = 200;           //默认宽度
$.fn.combotree.defaults.panelWidth = 200;

//配置DataGrid
$.fn.datagrid.defaults.striped = true;          //隔行变色
$.fn.datagrid.defaults.selectOnCheck = false;
$.fn.datagrid.defaults.checkOnSelect = false; //点击行时：是否选取checkbox
$.fn.datagrid.defaults.singleSelect = true;   //点击行时：true：只能选择一行  false：选择多行

//配置弹出窗口
$.fn.window.defaults.collapsible = false;     //折叠功能
$.fn.window.defaults.minimizable = false;     //最小化
$.fn.window.defaults.maximizable = false;     //最大化
$.fn.window.defaults.resizable = false;     //拖动改变大小

/**
* 校验规则扩展
*/
$.extend($.fn.validatebox.defaults.rules, {
    combobox: {
        validator: function (value, param) {
            return value != '请选择';
        },
        message: '该输入项为必输项'
    },
    CHS: {
        validator: function (value, param) {
            return /^[\u0391-\uFFE5]+$/.test(value);
        },
        message: '请输入汉字'
    },
    ZIP: {
        validator: function (value, param) {
            return /^[1-9]\d{5}$/.test(value);
        },
        message: '邮政编码不存在'
    },
    QQ: {
        validator: function (value, param) {
            return /^[1-9]\d{4,10}$/.test(value);
        },
        message: 'QQ号码不正确'
    },
    age: {
        validator: function (value, param) {
            return /^(?:[1-9][0-9]?|1[01][0-9]|120)$/.test(value);
        },
        message: '小于120的数字'
    },
    mobile: {
        validator: function (value, param) {
            return /^((\(\d{2,3}\))|(\d{3}\-))?13\d{9}$/.test(value);
        },
        message: '手机号码不正确'
    },

    phone: {
        validator: function (value, param) {
            return /(\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$/.test(value);
        },
        message: '电话不正确'
    },

    number: {
        validator: function (value, param) {
            return /^\d+$/.test(value);
        },
        message: '请输入数字'
    },
    minNumber: {
        validator: function (value, param) {
            return value > param[0];
        },
        message: '该输入项必须大于{0}'
    },
    customRemote: {
        validator: function (value, param) {
            var postdata = {};
            postdata[param[1]] = value;
            var m_result = $.ajax({
                type: "POST",
                url: param[0],
                data: postdata,
                dataType: "json",
                async: false
            }).responseText;
            if (m_result == "false") {
                $.fn.validatebox.defaults.rules.customRemote.message = param[2];
                return false;
            }
            else {
                return true;
            }
        },
        message: ''
    }
});

$.extend($.fn.datagrid.methods, {
    editCell: function (jq, param) {
        return jq.each(function () {
            var opts = $(this).datagrid('options');
            var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
            var columnEditor = $(this).datagrid('getData').rows[param.index]['editor'];
            for (var i = 0; i < fields.length; i++) {
                var col = $(this).datagrid('getColumnOption', fields[i]);
                //col.editor1 = col.editor;
                if (fields[i] != param.field) {
                    col.editor = null;
                } else if (fields[i] == param.field && columnEditor) {
                    col.editor = columnEditor;
                }
            }
            $(this).datagrid('beginEdit', param.index);
            //for (var i = 0; i < fields.length; i++) {
            //    var col = $(this).datagrid('getColumnOption', fields[i]);
            //    col.editor = col.editor1;
            //}
        });
    },
    editSearchGridCell: function (jq, param) {
        return jq.each(function () {
            var opts = $(this).datagrid('options');
            var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
            var columnEditor = $(this).datagrid('getData').rows[param.index]['editor'];
            for (var i = 0; i < fields.length; i++) {
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor1 = col.editor;
                if (fields[i] != param.field) {
                    col.editor = null;
                } else if (fields[i] == param.field && columnEditor && fields[i] == 'value') {
                    col.editor = columnEditor;
                } else if (fields[i] == param.field && columnEditor && fields[i]!= 'value') {
                    col.editor = col.editor1;
                }
            }
            $(this).datagrid('beginEdit', param.index);
            for (var i = 0; i < fields.length; i++) {
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor = col.editor1;
            }
        });
    }
});

/**
* From扩展
* getData 获取数据方法
*
* @param {Object} jq
* @param {Object} params 设置为true的话，会把string型"true"和"false"字符串值转化为boolean型。
*
* getQueryParams 获取查询条件方法
*
* @param {Object} jq
* @param {Object} params 设置为true的话，会把string型"true"和"false"字符串值转化为boolean型。
*/
$.extend($.fn.form.methods, {
    getData: function (jq, params) {
        var formArray = jq.serializeArray();
        var oRet = {};
        for (var i in formArray) {
            if (typeof (oRet[formArray[i].name]) == 'undefined') {
                if (params) {
                    oRet[formArray[i].name] = (formArray[i].value == "true" || formArray[i].value == "false") ? formArray[i].value == "true" : formArray[i].value;
                }
                else {
                    oRet[formArray[i].name] = formArray[i].value;
                }
            }
            else {
                if (params) {
                    oRet[formArray[i].name] = (formArray[i].value == "true" || formArray[i].value == "false") ? formArray[i].value == "true" : formArray[i].value;
                }
                else {
                    oRet[formArray[i].name] += "," + formArray[i].value;
                }
            }
        }
        return oRet;
    },
    getQueryParams: function (jq, params) {
        var formArray = jq.serializeArray();
        var oRet = {};
        var generateItem = function (name, value, method, orGroup) {
            var expression = '';
            expression = '[' + method + ']';
            if (orGroup) {
                expression += '{' + orGroup + '}';
            }
            expression += name;
            oRet[expression] = value;
        }
        for (var i in formArray) {
            var queryStr = $('#' + formArray[i].name).data('query');
            if (queryStr.substring(0, 1) != '{') {
                queryStr = '{' + queryStr + '}';
            }
            var temp = '', name = '', method = '', orGroup = '', value = '';
            var query = (new Function('return ' + queryStr))();
            method = query.method || 'Equal';
            orGroup = query.orGroup;
            name = query.name;
            value = formArray[i].value;
            if (typeof name == 'string') {
                generateItem(name, value, method, orGroup);
            } else if (Array.isArray(name)) {
                var arrNames = name;
                for (var i = 0; i < arrNames.length; i++) {
                    generateItem(arrNames[i], value, method, orGroup);
                }
            }
            //if (params) {
            //    oRet[name] = (formArray[i].value == "true" || formArray[i].value == "false") ? formArray[i].value == "true" : formArray[i].value;
            //}
            //else {
            //    oRet[name] = formArray[i].value;
            //}
        }

        return oRet;
    }
});

/**
* GridTree扩展
* simpleData加载
*/
$.fn.treegrid.defaults.loadFilter = function (data, parent) {
    var opt = $(this).data().treegrid.options;
    var idFiled,
    textFiled,
    parentField;
    if (opt.parentField) {
        idFiled = opt.idField || 'id';
        textFiled = opt.treeField || 'text';
        parentField = opt.parentField;
        var i, l,
       treeData = [],
       tmpMap = [];
        for (i = 0, l = data.length; i < l; i++) {
            tmpMap[data[i][idFiled]] = data[i];
        }
        for (i = 0, l = data.length; i < l; i++) {
            if (tmpMap[data[i][parentField]] && data[i][idFiled] != data[i][parentField]) {
                if (!tmpMap[data[i][parentField]]['children'])
                    tmpMap[data[i][parentField]]['children'] = [];
                data[i]['text'] = data[i][textFiled];
                tmpMap[data[i][parentField]]['children'].push(data[i]);
            } else {
                data[i]['text'] = data[i][textFiled];
                treeData.push(data[i]);
            }
        }
        return treeData;
    }
    return data;
};


/**
* Tree扩展
* simpleData加载
*/
$.fn.tree.defaults.loadFilter = function (data, parent) {
    var opt = $(this).data().tree.options;
    var idFiled,
    textFiled,
    parentField;
    if (opt.parentField) {
        idFiled = opt.idField || 'id';
        textFiled = opt.textFiled || 'text';
        parentField = opt.parentField;
        var i, l,
       treeData = [],
       tmpMap = [];
        for (i = 0, l = data.length; i < l; i++) {
            tmpMap[data[i][idFiled]] = data[i];
        }
        for (i = 0, l = data.length; i < l; i++) {
            if (tmpMap[data[i][parentField]] && data[i][idFiled] != data[i][parentField]) {
                if (!tmpMap[data[i][parentField]]['children'])
                    tmpMap[data[i][parentField]]['children'] = [];
                data[i]['text'] = data[i][textFiled];
                tmpMap[data[i][parentField]]['children'].push(data[i]);
            } else {
                data[i]['text'] = data[i][textFiled];
                treeData.push(data[i]);
            }
        }
        return treeData;
    }
    return data;
};


/**
* Tree扩展
* simpleData加载
*/
$.fn.combotree.defaults.loadFilter = function (data, parent) {
    var opt = $(this).data().tree.options;
    var idFiled,
    textFiled,
    parentField;
    if (opt.parentField) {
        idFiled = opt.idField || 'id';
        textFiled = opt.textFiled || 'text';
        parentField = opt.parentField;
        var i, l,
       treeData = [],
       tmpMap = [];
        for (i = 0, l = data.length; i < l; i++) {
            tmpMap[data[i][idFiled]] = data[i];
        }
        for (i = 0, l = data.length; i < l; i++) {
            if (tmpMap[data[i][parentField]] && data[i][idFiled] != data[i][parentField]) {
                if (!tmpMap[data[i][parentField]]['children'])
                    tmpMap[data[i][parentField]]['children'] = [];
                data[i]['text'] = data[i][textFiled];
                tmpMap[data[i][parentField]]['children'].push(data[i]);
            } else {
                data[i]['text'] = data[i][textFiled];
                treeData.push(data[i]);
            }
        }
        return treeData;
    }
    return data;
};




/*
lookup控件
version: 1.0
*/
(function ($) {

    // 创建控件DOM
    function create(target) {
        var id = $(target).attr('id');

        if (!id) {
            id = 'lookup_' + new Date().getTime();
            $(target).attr('id', id);
        }

        $(target).addClass('combo-f').hide();

        var lookup = $('<span class="combo"></span>').insertAfter(target);
        var textbox = $('<input type="text" class="combo-text" />').appendTo(lookup);
        var arrow = $("<span><span class=\"combo-arrow \"></span></span>").appendTo(lookup);
        var valbox = $("<input type=\"hidden\" class=\"combo-value\">").appendTo(lookup);

        lookup.addClass('lookup');



        var state = $.data(target, 'lookup');

        // 添加图标
        if (state.options.iconCls) {
            arrow.find('.combo-arrow').addClass(state.options.iconCls);
        }
        else {
            arrow.find('.combo-arrow').addClass('icon-search');
        }

        // 创建 dialog
        var _dialogOpts = {
            closed: true,
            title: state.options.title,
            onClose: function () {
                $(valbox).val($(state.dialog).find('.dialog-value').val());
                $(textbox).val($(state.dialog).find('.dialog-text').val());
            }
        }

        var name = $(target).attr("name");
        if (name) {
            lookup.find("input.combo-value").attr("name", name);
            $(target).removeAttr("name").attr("comboName", name);
        }
        textbox.attr("autocomplete", "off");

        arrow.on('click', function () {
            if (!state.dialog) {
                state.dialog = $(state.options.dialog).dialog(_dialogOpts);
            }
            state.dialog.dialog('open');
        });

        state.textbox = textbox;
        state.valbox = valbox;


    }

    $.fn.lookup = function (options, param) {
        if (typeof options == 'string') {
            var method = $.fn.lookup.methods[options];
            if (method) {
                return method(this, param);
            } else {
                return this.lookup(options, param);
            }
        }

        options = options || {};

        return this.each(function () {
            var state = $.data(this, 'lookup');
            if (state) {
                $.extend(state.options, options);
                create(this);
            }
            else {
                $.data(this, 'lookup', { options: $.extend({}, $.fn.lookup.defaults, options) });
                create(this);
            }
        })

    }


    $.fn.lookup.methods = {
        open: function () { },
        close: function (jq) {
            return jq.each(function () {
                var state = $.data(this, 'lookup');
                state.dialog.dialog('close');
            });
        },
        setValue: function (jq, val) {
            return jq.each(function () {
                var state = $.data(this, 'lookup');
                state.valbox.val(val);
                state.textbox.val(val);
            });

        },
        getValue: function (jq) {
            var state = $.data(jq[0], 'lookup');
            return state.valbox.val();

        },
        setText: function (jq, text) {
            return jq.each(function () {
                var state = $.data(this, 'lookup');
                state.textbox.val(text);
            });

        },
        getText: function (jq) {
            var state = $.data(jq[0], 'lookup');
            return state.textbox.val();
        }
    }

    $.fn.lookup.defaults = {
        iconCls: '',
        width: 120, height: 'auto',
        dialog: {
            title: '选择',
            width: 400, height: 300
        },
        onOpened: function (target) {
        }
    }

})(jQuery);

$.extend($.fn.datagrid.defaults.editors, {
    lookup: {
        init: function (container, options) {
            var lookup = $('<input type="text">').appendTo(container);
            lookup.lookup(options || {});
            return lookup;
        },
        getValue: function (target) {
            return $(target).lookup('getValue');
        },
        setValue: function (target, value) {

            return $(target).lookup('setValue', value);
        },
        resize: function (target, width) {
            var input = $(target);
            var tb = $(".combo-text");
            if ($.boxModel) {
                var w = width - (input.outerWidth() - input.width());
                input.width(w);
                tb.width(w - 24);
            } else {
                input.width(width - 2);
                tb.width(width - 24);
            }
        }
    }
});